<?php
declare(strict_types=1);

namespace app\command;

use app\common\model\order\ShopOrderModel;
use app\common\service\order\ShopOrderService;
use app\common\service\webscoket\CacheRedisService;
use app\job\OrderScheduleJob;
use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Log;
use think\facade\Queue;

/**
 * 订单上架定时任务
 * 调试模式开启：php think orderSchedule
 * 守护进程开启：php think orderSchedule -m d
 */
class OrderSchedule extends Command
{

    protected function configure()
    {
        // 指令配置
        $this->setName('orderSchedule')
            ->addArgument('action', Argument::OPTIONAL, "start|stop|restart|reload|status|connections", 'start')
            ->addOption('mode', 'm', Option::VALUE_OPTIONAL, '守护进程方式启动（-m d）')
            ->addOption('interval', 'i', Option::VALUE_OPTIONAL, '多长时间执行一次（秒）')
            ->setDescription('订单上架定时任务');
    }

    protected function execute(Input $input, Output $output)
    {
        // 指令输出
        $output->writeln('orderSchedule:execute');

        Log::write("订单上架：".date('Y-m-d H:i:s'));
        try {
            $where =[
                ['is_delete','=',0],
                ['status','=',ShopOrderModel::getStatus('o_listing',1)],
                ['estimate_advertising_time','<=',date('Y-m-d H:i:s')]
            ];
            $ids = CacheRedisService::sMembers('OrderScheduleListener');
            if($ids){
                $where[] = ['id','not in',$ids];
            }
            $list = ShopOrderService::getList($where,0,0,['estimate_advertising_time'=>'asc'],'id,status,old_status,is_self_selection,merchant_id');
            if($list){
                Log::write("订单上架数量：".count($list));
                CacheRedisService::sAdd('OrderScheduleListener',array_column($list,'id'));
                Queue::push(OrderScheduleJob::class, $list);
            }
        } catch (\Exception $e) {
            Log::error("订单上架报错：".$e->getMessage());
        }
    }


    public function stop()
    {
    }


}
